﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project2.容器
{
    internal class DictionaryStudy
    {
        private static void MainDictionaryStudy(string[] args)
        {
            Dictionary<string, int> ageDict = new Dictionary<string, int>();
            // 添加键值对到字典中
            ageDict.Add("Alice", 25);
            ageDict.Add("Bob", 30);
            //ageDict.Add("Bob", 20);
            ageDict.Add("Charlie", 22);
            PrintDict(ageDict);
            //改
            ageDict["Alice"] = 30;
            PrintDict(ageDict);

            var keyValuePairs = new[]
            {
                new KeyValuePair<string, int>("Alice", 90),
                new KeyValuePair<string, int>("Bob", 85),
                new KeyValuePair<string, int>("Charlie", 95)
            };

            //查
            int age1 = ageDict["Alice"];
            if (ageDict.ContainsKey("Bob"))
            {
                Console.WriteLine("Bob年龄是" + ageDict["Bob"]);
            }

            if (ageDict.TryGetValue("Bob", out var age))
            {
                Console.WriteLine("Bob年龄是" + age);
            }
            // 删除字典中的键值对
            ageDict.Remove("Charlie2");//不含有这个元素不会报错
            if (ageDict.ContainsKey("Charlie"))
            {
                ageDict.Remove("Charlie");
                Console.WriteLine("删除Charlie");
            }
            else
            {
                Console.WriteLine("没有这个人，无法删除");
            }
            Console.WriteLine("entryCount=" + ageDict.Count);

            if (ageDict.ContainsValue(20))
            {
                Console.WriteLine("有人的年龄是20");
            }

            ageDict.Clear();
        }

        public static void PrintDict(Dictionary<string, int> dict)
        {
            foreach (var pairs in dict)
            {
                Console.Write(pairs.Key + "  " + pairs.Value + ",   ");
            }

            foreach (var key in dict.Keys)
            {
                Console.WriteLine(key);
            }
            foreach (var v in dict.Values)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine();
        }
    }
}